<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Curl;
use app\common\lib\Num;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Time;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;

class Comments
{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\Comments();
    }

    public function getListByWhere($where,$page,$limit,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    public function getListByType($where,$type,$page,$limit,$keyword,$departmentId,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];

        switch ($type){
            case 1:
                //我收到的评价
                //雇主及工人对公司的评价
                //user是user associated是company
                $where[] = ['type','in',[2,3]];
                $where[] = ['associated_id','=',$departmentId];//人力资源公司显示公司收到的评价
                break;
            case 2:
                //我发出的评价
                $where[] = ['type','in',[1]];//公司评价工人
                $where[] = ['user_id','=',$departmentId];//人力资源公司显示公司发出的评价
                break;
            case 3:
                //所有评价
                $where[] = ['type','in',[1,2,3]];
                break;
        }
        $dataList = $this->getListByWhere($where,0,0,$field);
        $totalCount = count($dataList);

        //取出涉及的人力资源和用户信息
        $departmentIdArr = [];
        $userIdArr = [];
        $workIdArr = [];
        if (!empty($dataList)){
            foreach ($dataList as $k=>$v){
                if ($v['type'] == 1){
                    //公司评价工人，associated_id为工人 user_id为公司
                    $departmentIdArr[] = $v['user_id'];
                    $userIdArr[] = $v['associated_id'];
                }elseif(in_array($v['type'],[2,3])){
                    //2雇主评价公司，associated_id为公司 user_id为用工方
                    //3工人评价公司，associated_id为公司 user_id为工人
                    $departmentIdArr[] = $v['associated_id'];
                    $userIdArr[] = $v['user_id'];
                }

                $workIdArr[] = $v['work_id'];
            }
            if (!empty($departmentIdArr)){
                $departmentList = (new Department())->getListByWhere([['id','in',$departmentIdArr]],0,0,'id,name');
                $departmentArr = Arr::getKeyValueByTwoArray($departmentList,'','id',2);
            }
            if (!empty($userIdArr)){
                $userList = (new User())->getListByWhere([['id','in',$userIdArr]],0,0,'id,name,sex');
                $userArr = Arr::getKeyValueByTwoArray($userList,'','id',2);
            }
            if (!empty($workIdArr)){
                $workList = (new Work())->getListByWhere([['id','in',$workIdArr]],0,0,'id,name');
                $workArr = Arr::getKeyValueByTwoArray($workList,'','id',2);
            }
            foreach ($dataList as $k=>$v){
                $dataList[$k]['work'] = $workArr[$v['work_id']] ?? [];

                if ($v['type'] == 1){
                    //公司评价工人，associated_id为工人 user_id为公司
                    $dataList[$k]['user'] = $departmentArr[$v['user_id']] ?? [];
                    if (isset($userArr[$v['associated_id']])){
                        $dataList[$k]['associated'] = $userArr[$v['associated_id']];
                        $dataList[$k]['associated']['type_text'] = '工人';

                        //dump($keyword,strpos($dataList[$k]['associated']['name'],$keyword));
                        if(!empty($keyword) && !(strpos($dataList[$k]['associated']['name'],$keyword)!==false)){
                            unset($dataList[$k]);
                        }
                    }
                }elseif($v['type'] == 2){
                    //2雇主评价公司，associated_id为公司 user_id为用工方
                    $dataList[$k]['user'] = $userArr[$v['user_id']] ?? [];
                    if (!empty($dataList[$k]['user'])) $dataList[$k]['user']['type_text'] = '用工方';
                    if (isset($departmentArr[$v['associated_id']])){
                        $dataList[$k]['associated'] = $departmentArr[$v['associated_id']];

                        //dump($keyword,strpos($dataList[$k]['associated']['name'],$keyword));
                        if(!empty($keyword) && !(strpos($dataList[$k]['associated']['name'],$keyword)!==false)){
                            unset($dataList[$k]);
                        }
                    }
                }elseif($v['type'] == 3){
                    //3工人评价公司，associated_id为公司 user_id为工人
                    $dataList[$k]['user'] = $userArr[$v['user_id']] ?? [];
                    if (!empty($dataList[$k]['user'])) $dataList[$k]['user']['type_text'] = '工人';
                    if (isset($departmentArr[$v['associated_id']])){
                        $dataList[$k]['associated'] = $departmentArr[$v['associated_id']];

                        //dump($keyword,strpos($dataList[$k]['associated']['name'],$keyword));
                        if(!empty($keyword) && !(strpos($dataList[$k]['associated']['name'],$keyword)!==false)){
                            unset($dataList[$k]);
                        }
                    }
                }
            }

            $totalCount = count($dataList);

            //数组分页
            $start = ($page - 1) * $limit;
            $dataList = array_values($dataList);
            $dataList = array_slice($dataList,$start,$limit);
        }
        return ['list'=>$dataList,'count'=>$totalCount];
    }

    public function getListByTypeOther($where,$type,$page,$limit,$keyword,$departmentId,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];

        $linkArr = [];
        switch ($type){
            case 1:
                //我收到的评价
                //雇主及工人对公司的评价
                //user是user associated是company
                $where[] = ['type','in',[2,3]];
                $where[] = ['associated_id','=',$departmentId];//人力资源公司显示公司收到的评价
                $linkArr = [
                    'userLink'=>'user',
                    'associatedLink'=>'department',
                    'userLinkField'=>['id','name','sex','avatar'],
                    'associatedLinkField'=>['id','name'],
                ];
                break;
            case 2:
                //我发出的评价
                $where[] = ['type','in',[1]];//公司评价工人
                $where[] = ['user_id','=',$departmentId];//人力资源公司显示公司发出的评价
                $linkArr = [
                    'userLink'=>'departmentUser',
                    'associatedLink'=>'associatedUser',
                    'userLinkField'=>['id','name'],
                    'associatedLinkField'=>['id','name','sex','avatar'],
                ];
                break;
            case 3:
                //所有评价
                $where[] = ['type','in',[1,2,3]];
                break;
        }

        $list = $this->getPageTableJoinList($page,$limit,$where,$linkArr);
        return $list;
    }

    public function getCountByWhere($where,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        $list = $this->model->getNormalListByWhere($where,$field);

        return count($list);
    }

    public function handlerCalcTotalScore($type,$associated_id){
        $result = 0;

        $where[] = ['status','=',config("status.mysql.table_normal")];

        $linkArr = [];
        switch ($type){
            //1公司总分 2工人总分
            case 1:
                $where[] = ['type','in',[2,3]];
                break;
            case 2:
                $where[] = ['type','in',[1]];//公司评价工人
                break;
        }
        $where[] = ['associated_id','=',$associated_id];

        $list = $this->getListByWhere($where,0,0,'score');
        if (!empty($list)){
            $scoreArr = array_column($list,'score');
            $scoreTotal = array_sum($scoreArr);
            $result = round($scoreTotal / count($scoreArr),1);
        }
        return $result;
    }

    /**
     * @param $page
     * @param $limit
     * @param $where
     * @param array $linkArr
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPageTableJoinList($page,$limit,$where,$linkArr=[]): array
    {
        $userField = $linkArr['userLinkField'];
        $associatedField = $linkArr['associatedLinkField'];
        $workField = ['id','name'];

        $list=$this->model->field(['id','associated_id','type','work_id','user_id','work_rob_id','score','comments','create_time','update_time'])->with([$linkArr['userLink']=>function($query) use ($userField){
            $query->field($userField);
        },$linkArr['associatedLink']=>function($query) use ($associatedField){
        $query->field($associatedField);
    },'work'=>function($query) use ($workField){
            $query->field($workField);
        }])->where($where)->page($page,$limit)->order('id desc')->select();
        $list=$list->isEmpty()?[]:$list->toArray();

        if (!empty($list)){
            foreach ($list as $k=>$v){
                //身份
                switch ($v['type']){
                    case 1:
                        $list[$k]['user'] = $list[$k]['departmentUser'];
                        $list[$k]['associated'] = $list[$k]['associatedUser'];
                        $list[$k]['associated']['type_text'] = '工人';break;
                    case 2:
                        $list[$k]['associated'] = $list[$k]['department'];
                        $list[$k]['user']['type_text'] = '用工方';break;
                    case 3:
                        $list[$k]['associated'] = $list[$k]['department'];
                        $list[$k]['user']['type_text'] = '工人';break;
                }
            }
        }
        $total=$this->model->field(['id'])->with([$linkArr['userLink']=>function($query) use ($userField){
            $query->field($userField);
        },$linkArr['associatedLink']=>function($query) use ($associatedField){
            $query->field($associatedField);
        },'work'=>function($query) use ($workField){
            $query->field($workField);
        }])->where($where)->count();
        return ['list'=>$list,'count'=>$total];
    }

    public function getNormalById($id)
    {
        $data = $this->model->getById($id);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $data->toArray();
    }

    public function getNormalByField($field,$value): array
    {
        $data = $this->model->getNormalByField($field, $value);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $data->toArray();
    }

    public function getNormalByWhere($where,$field='*'): array
    {
        $data = $this->model->getNormalByWhere($where, $field);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $data->toArray();
    }

    /**
     * 公司评价工人
     * @param $ids
     * @param $work_id
     * @return bool
     */
    public function handlerComment($data): bool
    {
        if (empty($data)){
            throw new Exception('参数错误');
        }

        $workBis = new Work();
        $workInfo = $workBis->getNormalById($data['work_id']);
        if (empty($workInfo)){
            throw new Exception('零活不存在');
        }
        if ($workInfo['process_status'] != 2){
            throw new Exception('只有完工的零活才能评价');
        }

        $workRobBis = new WorkRob();
        $workRobInfo = $workRobBis->getNormalById($data['work_rob_id']);
        if (empty($workRobInfo)){
            throw new Exception('抢活记录不存在');
        }

        $depBis = new Department();
        $depInfo = $depBis->getNormalById($data['user_id']);
        if (empty($depInfo)){
            throw new Exception('人力资源公司不存在');
        }

        $userBis = new User();
        $userInfo = $userBis->getNormalUserById($data['associated_id']);
        if (empty($userInfo)){
            throw new Exception('求职工不存在');
        }
        if ($workRobInfo['user_id'] != $data['associated_id'] || $workRobInfo['is_employed'] != 1){
            throw new Exception('求职者异常或未被派遣');
        }

        $mapComments = [
            ['associated_id','=',$data['associated_id']],
            ['user_id','=',$data['user_id']],
            ['type','=',1],
            ['work_id','=',$data['work_id']],
            ['work_rob_id','=',$data['work_rob_id']],
        ];
        $commentsBis = new Comments();
        $commentsInfo = $commentsBis->getNormalByWhere($mapComments,'id,status');
        if (empty($commentsInfo)){
            //无则新增
            $data['status'] = config('status.mysql.table_normal');
            $data['create_time'] = time();

            try {
                $res = $this->model->save($data);
            } catch (\Exception $e) {
                throw new Exception($e->getMessage()."数据库内部异常");
            }
        }else{
            //有则更新
            $commentId = $commentsInfo['id'];
            $updateData = [
                'score' => $data['score'],
                'comments' => $data['comments'],
            ];

            try {
                $res = $this->model->updateById($commentId,$updateData);
            } catch (\Exception $e) {
                throw new Exception("数据库内部异常");
            }

        }
        return $res;
    }

    /**
     * 用工方/工人评价公司
     * @param $user_id
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function handlerCommentDepartment($user_id,$data): bool
    {
        if (empty($data) || empty($user_id)){
            throw new Exception('参数错误');
        }

        $workBis = new Work();
        $workInfo = $workBis->getNormalById($data['work_id']);
        if (empty($workInfo)){
            throw new Exception('零活不存在');
        }
        if ($workInfo['process_status'] != 2){
            throw new Exception('只有完工的零活才能评价');
        }

        if ($data['type'] == 3){
            //工人评价公司
            $workRobBis = new WorkRob();
            $workRobInfo = $workRobBis->getNormalById($data['work_rob_id']);
            if (empty($workRobInfo)){
                throw new Exception('抢活记录不存在');
            }
        }

        $depBis = new Department();
        $depInfo = $depBis->getNormalById($data['associated_id']);
        if (empty($depInfo)){
            throw new Exception('人力资源公司不存在');
        }

        $userBis = new User();
        $userInfo = $userBis->getNormalUserById($user_id);
        if (empty($userInfo)){
            throw new Exception('用户不存在');
        }
        if ($data['type'] == 3){
            if ($workRobInfo['user_id'] != $user_id || $workRobInfo['is_employed'] != 1){
                throw new Exception('用户异常或未被派遣');
            }
        }

        $mapComments = [
            ['associated_id','=',$data['associated_id']],
            ['user_id','=',$user_id],
            ['type','=',$data['type']],
            ['work_id','=',$data['work_id']],
            ['work_rob_id','=',$data['work_rob_id']],
        ];
        $commentsBis = new Comments();
        $commentsInfo = $commentsBis->getNormalByWhere($mapComments,'id,status');

        //20230531修改为只能评价一次
        if (!empty($commentsInfo)){
            throw new Exception('请勿重复评价');
        }

        $data['user_id'] = $user_id;
        $data['status'] = config('status.mysql.table_normal');
        $data['create_time'] = time();
        try {
            $res = $this->model->save($data);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage()."数据库内部异常");
        }

        //记录完评价表后更新人力资源公司表中综合评分
        //2用工方评价 3工人评价
        $mapCommentsAll = [
            ['type','=',$data['type']],
            ['associated_id','=',$data['associated_id']]
        ];
        $commentsList = $commentsBis->getListByWhere($mapCommentsAll,0,0,'id,score');
        if (!empty($commentsList)){
            $score_total = array_sum(array_column($commentsList,'score'));
            $score_avg = round($score_total / count($commentsList),1);

            if (in_array($data['type'],[2,3])){
                $saveDepField = $data['type'] == 2 ? 'employer_score' : 'workers_score';

                $saveDep = [];
                $saveDep['id'] = $data['associated_id'];
                $saveDep['update_time'] = time();
                $saveDep[$saveDepField] = $score_avg;

                $departmentBis = new Department();
                $departmentBis->save($saveDep);
            }
        }

        /*if (empty($commentsInfo)){
            //无则新增
            $data['status'] = config('status.mysql.table_normal');
            $data['create_time'] = time();

            try {
                $res = $this->model->save($data);
            } catch (\Exception $e) {
                throw new Exception($e->getMessage()."数据库内部异常");
            }
        }else{
            //有则更新
            $commentId = $commentsInfo['id'];
            $updateData = [
                'score' => $data['score'],
                'comments' => $data['comments'],
            ];

            try {
                $res = $this->model->updateById($commentId,$updateData);
            } catch (\Exception $e) {
                throw new Exception("数据库内部异常");
            }
        }*/
        return $res;
    }

    //转义text
    public function resetTextList($list){
        if (empty($list)){
            return [];
        }

        $userWhere = [
            ['id','in',array_column($list,'user_id')]
        ];
        //评价者用户
        $userList = (new User())->getListByWhere($userWhere,0,0,'id,name,avatar');
        $userArr = Arr::getKeyValueByTwoArray($userList,'','id',2);
        //评价者公司
        $departmentList = (new Department())->getListByWhere($userWhere,0,0,'id,name,logo');
        $departmentArr = Arr::getKeyValueByTwoArray($departmentList,'','id',2);

        //零活
        $workWhere = [
            ['id','in',array_column($list,'work_id')]
        ];
        $workList = (new Work())->getListByWhere($workWhere,0,0,'id,name');
        $workArr = Arr::getKeyValueByTwoArray($workList,'','id',2);

        foreach ($list as $k=>$v){
            //$list[$k]['create_time_text'] = Time::formatTheTime($v['create_time'],'s');

            if ($v['type'] == 1){
                //公司评价工人
                $list[$k]['user'] = $departmentArr[$v['user_id']] ?? [];
            }elseif(in_array($v['type'],[2,3])){
                //用工方/工人评价公司
                if(isset($userArr[$v['user_id']])){
                    $userArr[$v['user_id']]['name'] = Str::dealSecretString($userArr[$v['user_id']]['name']);
                }
                $list[$k]['user'] = $userArr[$v['user_id']] ?? [];
            }
            $list[$k]['work'] = $workArr[$v['work_id']] ?? [];
        }
        return $list;
    }
}
